using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CPlatePrintSys.Domain.Models;
using CPlatePrintSys.Domain.Services;
using CPlatePrintSys.Infrastructure.Repositories;

namespace CPlatePrintSys.Application.Services
{
    /// <summary>
    /// 用户应用服务实现
    /// 协调领域对象和基础设施，实现用户相关的业务逻辑
    /// </summary>
    public class UserService : IUserService
    {
        private readonly IUserRepository _userRepository;

        public UserService(IUserRepository userRepository)
        {
            _userRepository = userRepository;
        }

        public async Task<User> GetUserByIdAsync(int id)
        {
            return await _userRepository.GetByIdAsync(id);
        }

        public async Task<User> GetUserByUsernameAsync(string username)
        {
            return await _userRepository.GetByUsernameAsync(username);
        }

        public async Task<IEnumerable<User>> GetAllUsersAsync()
        {
            return await _userRepository.GetAllAsync();
        }

        public async Task<User> CreateUserAsync(User user)
        {
            // 验证用户名是否已存在
            if (await _userRepository.IsUsernameExistsAsync(user.Username))
                throw new System.InvalidOperationException("用户名已存在");

            // 验证工号是否已存在
            if (!string.IsNullOrEmpty(user.JobNumber) && await _userRepository.IsJobNumberExistsAsync(user.JobNumber))
                throw new System.InvalidOperationException("工号已存在");

            return await _userRepository.AddAsync(user);
        }

        public async Task UpdateUserAsync(User user)
        {
            var existingUser = await _userRepository.GetByIdAsync(user.Id);
            if (existingUser == null)
                throw new System.InvalidOperationException("用户不存在");

            // 检查用户名是否被其他用户使用
            var userWithSameUsername = await _userRepository.GetByUsernameAsync(user.Username);
            if (userWithSameUsername != null && userWithSameUsername.Id != user.Id)
                throw new System.InvalidOperationException("用户名已被其他用户使用");

            // 检查工号是否被其他用户使用
            if (!string.IsNullOrEmpty(user.JobNumber))
            {
                var userWithSameJobNumber = await _userRepository.GetByJobNumberAsync(user.JobNumber);
                if (userWithSameJobNumber != null && userWithSameJobNumber.Id != user.Id)
                    throw new System.InvalidOperationException("工号已被其他用户使用");
            }

            await _userRepository.UpdateAsync(user);
        }

        public async Task DeleteUserAsync(int id)
        {
            await _userRepository.DeleteAsync(id);
        }

        public async Task<bool> ValidateUserCredentialsAsync(string username, string password)
        {
            return await _userRepository.ValidateCredentialsAsync(username, password);
        }

        public async Task<bool> IsUsernameExistsAsync(string username)
        {
            return await _userRepository.IsUsernameExistsAsync(username);
        }

        public async Task<bool> IsJobNumberExistsAsync(string jobNumber)
        {
            return await _userRepository.IsJobNumberExistsAsync(jobNumber);
        }

        public async Task UpdateLastLoginAsync(int userId)
        {
            await _userRepository.UpdateLastLoginAsync(userId);
        }

        public async Task<IEnumerable<User>> GetUsersByRoleAsync(string role)
        {
            var users = await _userRepository.GetAllAsync();
            return users.Where(u => u.Role.ToString() == role);
        }

        public async Task<int> GetActiveUserCountAsync()
        {
            var users = await _userRepository.GetAllAsync();
            return users.Count(u => u.IsActive);
        }
    }
} 